
package com.jf.cloud.product.service.impl;

import com.jf.cloud.api.multishop.feign.ShopSubstituteSalesFeignClient;
import com.jf.cloud.api.supplier.feign.SupplierDetailFeignClient;
import com.jf.cloud.api.supplier.vo.SupplierApiDetailVO;
import com.jf.cloud.common.constant.StatusEnum;
import com.jf.cloud.common.database.dto.PageDTO;
import com.jf.cloud.common.database.util.PageUtil;
import com.jf.cloud.common.database.vo.PageVO;
import com.jf.cloud.common.product.constant.ContentKey;
import com.jf.cloud.common.product.constant.ContentValue;
import com.jf.cloud.common.product.constant.SupplierSpuChangeType;
import com.jf.cloud.common.product.dto.SkuDTO;
import com.jf.cloud.common.product.vo.SkuVO;
import com.jf.cloud.common.product.vo.SpuVO;
import com.jf.cloud.common.response.ServerResponseEntity;
import com.jf.cloud.common.security.AuthUserContext;
import com.jf.cloud.common.util.PriceUtil;
import com.jf.cloud.common.vo.ShopSubstituteSalesVO;
import com.jf.cloud.common.product.constant.SpuStatus;
import com.jf.cloud.product.dto.SpuSupplierChangeLogDTO;
import com.jf.cloud.product.mapper.SkuLangMapper;
import com.jf.cloud.product.mapper.SkuMapper;
import com.jf.cloud.product.mapper.SpuMapper;
import com.jf.cloud.product.mapper.SpuSupplierChangeLogMapper;
import com.jf.cloud.product.model.Sku;
import com.jf.cloud.product.model.SpuSupplierChangeLog;
import com.jf.cloud.product.service.SkuService;
import com.jf.cloud.product.service.SpuAttrValueService;
import com.jf.cloud.product.service.SpuExtensionService;
import com.jf.cloud.product.service.SpuSupplierChangeLogService;
import com.jf.cloud.product.vo.SpuSupplierChangeLogVO;
import ma.glasnost.orika.MapperFacade;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.stream.Collectors;

/**
 * 商品供应商变更记录
 *
 * @author zz
 * @date 2022-06-22 16:57:27
 */
@Service
public class SpuSupplierChangeLogServiceImpl implements SpuSupplierChangeLogService {

    @Autowired
    private SpuSupplierChangeLogMapper spuSupplierChangeLogMapper;
    @Autowired
    private SpuMapper spuMapper;
    @Autowired
    private SkuService skuService;
    @Autowired
    private SkuMapper skuMapper;
    @Autowired
    private MapperFacade mapperFacade;
    @Autowired
    private SkuLangMapper skuLangMapper;
    @Autowired
    private SpuAttrValueService spuAttrValueService;
    @Autowired
    private SpuExtensionService spuExtensionService;
    @Autowired
    private ShopSubstituteSalesFeignClient shopSubstituteSalesFeignClient;
    @Autowired
    private SupplierDetailFeignClient supplierDetailFeignClient;
    @Override
    public PageVO<SpuSupplierChangeLogVO> page(PageDTO pageDTO) {
        Long shopId = AuthUserContext.get().getTenantId();
        //获取供应商商品id列表
        List<Long> supplierSpuId = spuMapper.getSupplierSpuId(shopId);
        //获取供应商名称
        if (supplierSpuId.size() > 0){
            PageVO<SpuSupplierChangeLogVO> pageVO = PageUtil.doPage(pageDTO, () -> spuSupplierChangeLogMapper.listBySpuIds(supplierSpuId));
            List<SpuSupplierChangeLogVO> spuSupplierChangeLogVOList = pageVO.getList();
            //供应商id
            List<Long> supplierIdList = spuSupplierChangeLogVOList.stream().map(e -> e.getSupplierId()).collect(Collectors.toList());
            //获取供应商名称
            List<SupplierApiDetailVO> supplierApiDetailVOList = supplierDetailFeignClient.listBySupplierIds(supplierIdList).getData();
            Map<Long, String> supplierNameMap = supplierApiDetailVOList.stream().collect(Collectors.toMap(SupplierApiDetailVO::getSupplierId, SupplierApiDetailVO::getSupplierName));
            //获取供应商商品对应的代销商品id
            List<Long> supplieSpuIds = spuSupplierChangeLogVOList.stream().map(e -> e.getSpuId()).collect(Collectors.toList());
            if (supplieSpuIds.size() == 0){
                return pageVO;
            }
            List<SpuVO> spuVOS = spuMapper.listSpuByShopIdAndSupplierSpuId(shopId, supplieSpuIds);
            Map<Long, Long> collect = spuVOS.stream().collect(Collectors.toMap(SpuVO::getSupplierSpuId, SpuVO::getSpuId));
            for (SpuSupplierChangeLogVO spuSupplierChangeLogVO : spuSupplierChangeLogVOList) {
                //设置供应商名称
                spuSupplierChangeLogVO.setSupplierName(supplierNameMap.get(spuSupplierChangeLogVO.getSupplierId()));
                spuSupplierChangeLogVO.setCommissionSpuId(collect.get(spuSupplierChangeLogVO.getSpuId()));
                if (Objects.equals(spuSupplierChangeLogVO.getChangeType(),SupplierSpuChangeType.PUT_SHELF.value())){
                    //上架
                    spuSupplierChangeLogVO.setContentKey(ContentKey.STATUS_CHANGE.value());
                    spuSupplierChangeLogVO.setContentValue(ContentValue.SPU_PUT.value());
                }
                if (Objects.equals(spuSupplierChangeLogVO.getChangeType(),SupplierSpuChangeType.OFF_SHELF.value())){
                    //下架
                    spuSupplierChangeLogVO.setContentKey(ContentKey.STATUS_CHANGE.value());
                    spuSupplierChangeLogVO.setContentValue(ContentValue.SPU_OFF.value());
                }
                if (Objects.equals(spuSupplierChangeLogVO.getChangeType(),SupplierSpuChangeType.SKU_MSG_CHANGE.value())){
                    //SKU描述变更
                    spuSupplierChangeLogVO.setContentKey(ContentKey.DESCRIBE_CHANGE.value());
                    spuSupplierChangeLogVO.setContentValue(ContentValue.SKU_CHANGE.value());
                }
                if (Objects.equals(spuSupplierChangeLogVO.getChangeType(),SupplierSpuChangeType.ADD_SKU.value())){
                    //新增sku
                    spuSupplierChangeLogVO.setContentKey(ContentKey.ELSE_CHANGE.value());
                    spuSupplierChangeLogVO.setContentValue(ContentValue.ADD_SKU.value());
                }
            }
            return pageVO;
        }
        return null;
    }

    @Override
    public SpuSupplierChangeLog getBySpuChangeId(Long spuChangeId) {
        return spuSupplierChangeLogMapper.getBySpuChangeId(spuChangeId);
    }

    @Override
    public void save(SpuSupplierChangeLog spuSupplierChangeLog) {
        spuSupplierChangeLogMapper.save(spuSupplierChangeLog);
    }

    @Override
    public void update(SpuSupplierChangeLog spuSupplierChangeLog) {
        spuSupplierChangeLogMapper.update(spuSupplierChangeLog);
    }

    @Override
    public void deleteById(Long spuChangeId) {
        spuSupplierChangeLogMapper.deleteById(spuChangeId);
    }


    @Override
    @Transactional(rollbackFor = Exception.class)
    public void syncSpu(Long shopId, List<SpuSupplierChangeLogDTO> spuSupplierChangeLog){
        Map<Integer, List<SpuSupplierChangeLogDTO>> collect = spuSupplierChangeLog.stream().collect(Collectors.groupingBy(SpuSupplierChangeLogDTO::getChangeType));
        //上架
        List<SpuSupplierChangeLogDTO> putShelf = collect.get(SupplierSpuChangeType.PUT_SHELF.value());
        if (!Objects.isNull(putShelf)){
            List<Long> putSupplierSpuId = putShelf.stream().map(e -> e.getSpuId()).collect(Collectors.toList());
            List<Long> putSpuId = spuMapper.getSpuIdByShopIdAndSupplierSpuId(shopId, putSupplierSpuId);
            spuMapper.batchChangeSpuStatus(putSpuId,SpuStatus.PUT_SHELF.value());
            spuSupplierChangeLog.removeAll(putShelf);
            spuMapper.batchChangeSynUpdate(putSpuId,1);
        }
        //下架
        List<SpuSupplierChangeLogDTO> offShelf = collect.get(SupplierSpuChangeType.OFF_SHELF.value());
        if (!Objects.isNull(offShelf)){
            List<Long> offSupplierSpuId = offShelf.stream().map(e -> e.getSpuId()).collect(Collectors.toList());
            List<Long> offSpuId = spuMapper.getSpuIdByShopIdAndSupplierSpuId(shopId, offSupplierSpuId);
            spuMapper.batchChangeSpuStatus(offSpuId,SpuStatus.OFF_SHELF.value());
            spuSupplierChangeLog.removeAll(offShelf);
            spuMapper.batchChangeSynUpdate(offSpuId,1);
        }
        for (SpuSupplierChangeLogDTO supplierChangeLog : spuSupplierChangeLog) {
            //获取到代销商品信息
            SpuVO spuVo = spuMapper.getSpuByShopIdAndSupplierSpuId(shopId, supplierChangeLog.getSpuId());
            //获取代销商品sku信息
            List<SkuVO> skuVOS = skuService.listSkuAllInfoBySpuId(spuVo.getSpuId(), false);
            //获取供应商品sku信息
            List<SkuVO> supplierSkuVOS = skuService.listSkuAllInfoBySpuId(supplierChangeLog.getSpuId(), false);
            //同步sku信息变更
            if (Objects.equals(SupplierSpuChangeType.SKU_MSG_CHANGE.value(),supplierChangeLog.getChangeType())){
                skuMsgChange(supplierSkuVOS,spuVo);
                spuMapper.changeSynUpdate(spuVo.getSpuId(),1);
            }
            //同步新增sku
            if (Objects.equals(SupplierSpuChangeType.ADD_SKU.value(),supplierChangeLog.getChangeType())){
                addSku(skuVOS,supplierSkuVOS,spuVo);
                spuMapper.changeSynUpdate(spuVo.getSpuId(),1);
            }
        }
    }

    /**
     * 同步sku信息变更
     * @param supplierSkuVOS
     * @param spuVo
     */
    public void skuMsgChange(List<SkuVO> supplierSkuVOS,SpuVO spuVo){
        List<Sku> skus = new ArrayList<>();
        for (SkuVO skuVO : supplierSkuVOS) {
            //根据供应商品skuId获取代销商品skuId
            Long skuId = skuMapper.getSkuIdBySupplierSkuId(skuVO.getSkuId(),spuVo.getSpuId());
            skuVO.setSpuId(spuVo.getSpuId());
            skuVO.setSkuId(skuId);
            //获取店铺代销设置设置销售价格
            Long priceFee = setPriceFee(skuVO);
            skuVO.setPriceFee(priceFee);
            skuVO.setMarketPriceFee(null);
            skus.add(mapperFacade.map(skuVO, Sku.class));
        }
        skuMapper.updateBatch(skus);
    }

    /**
     * 同步新增sku
     * @param skuVOS
     * @param supplierSkuVOS
     * @param spuVo
     */
    public void addSku(List<SkuVO> skuVOS,List<SkuVO> supplierSkuVOS,SpuVO spuVo){
        List<Long> skuIds = skuVOS.stream().map(e -> e.getSkuId()).collect(Collectors.toList());
        List<Long> supplierSkuIds = supplierSkuVOS.stream().map(e -> e.getSkuId()).collect(Collectors.toList());
        //获取供应商新增skuId
        supplierSkuIds.removeAll(skuIds);
        //获取供应商新增sku信息
        List<SkuVO> skuList = skuMapper.getSkuBatch(supplierSkuIds);
        List<SkuDTO> skuDtoS = new ArrayList<>();
        for (SkuVO skuVO : skuList) {
            skuVO.setSpuId(spuVo.getSpuId());
            //获取店铺代销设置设置销售价格
            Long priceFee = setPriceFee(skuVO);
            skuVO.setPriceFee(priceFee);
            skuDtoS.add(mapperFacade.map(skuVO, SkuDTO.class));
        }
        skuMapper.saveBatch(skuDtoS);
    }

    @Override
    public void insertBatchChangeStatus(List<Long> spuIds, Integer status) {
        if(status.equals(StatusEnum.ENABLE.value())){
            spuSupplierChangeLogMapper.insertBatch(spuIds, SupplierSpuChangeType.PUT_SHELF.value());
        }else if(status.equals(StatusEnum.DISABLE.value())){
            spuSupplierChangeLogMapper.insertBatch(spuIds, SupplierSpuChangeType.OFF_SHELF.value());
        }

    }

    @Override
    public void saveBatch(List<SpuSupplierChangeLog> spuSupplierChangeLogs) {
        spuSupplierChangeLogMapper.saveBatch(spuSupplierChangeLogs);
    }

    public Long setPriceFee(SkuVO skuVO){
        Long shopId = AuthUserContext.get().getTenantId();
        //获取商家代销设置
        ServerResponseEntity<ShopSubstituteSalesVO> salesType = shopSubstituteSalesFeignClient.getByShopSubstituteSalesId(shopId);
        ShopSubstituteSalesVO shopSubstituteSalesVO = salesType.getData();
        if (!Objects.isNull(shopSubstituteSalesVO)){
            if (shopSubstituteSalesVO.getSalesType() == 0){
                //智能设价计算售价
                Long price = 0L;
                if (shopSubstituteSalesVO.getSalesPriceType() == 0){
                    //按比例加价
                    price = PriceUtil.divideByBankerRounding(skuVO.getPriceFee() * shopSubstituteSalesVO.getSalesPrice(),10000) + skuVO.getPriceFee();
                }
                if (shopSubstituteSalesVO.getSalesPriceType() == 1){
                    //按固定数值加价
                    price = skuVO.getPriceFee() + shopSubstituteSalesVO.getSalesPrice();
                }
                return price;
            }
        }
        return 0L;
    }

//    @Override
//    @Transactional(rollbackFor = Exception.class)
//    public void importSpu(Long supplierSpuId) {
//        Long spuId = supplierSpuId;
//        Long shopId = AuthUserContext.get().getTenantId();
//        //查看是否已导入
//        SpuVO commissionSup = spuMapper.getSpuByShopIdAndSupplierSpuId(shopId, supplierSpuId);
//        if (!Objects.isNull(commissionSup)){
//            return;
//        }
//        //查找供应商spu信息
//        SpuVO spuVo = spuMapper.getBySpuId(spuId);
//        SpuDTO spuDTO = mapperFacade.map(spuVo, SpuDTO.class);
//        //商品状态默认为下架
//        spuDTO.setStatus(SpuStatus.OFF_SHELF.value());
//        //供应商商品类型：商家代销
//        spuDTO.setSupplierSpuType(SupplierSpuType.CONSIGNMENT.value());
//        //发货方式：供应商发货
//        spuDTO.setSupplierDeliveryType(SupplierDeliveryType.SUPPLIER_DELIVERY.value());
//        //关联商品商品id
//        spuDTO.setSupplierSpuId(spuVo.getSpuId());
//        //代销商品规格选择状态:全选
//        spuDTO.setSkuChoiceStatus(SkuChoiceStatus.ALL_CHOICE.value());
//        //供应商id
//        spuDTO.setSupplierId(spuVo.getSupplierId());
//        spuDTO.setShopId(shopId);
//        //代销商品无需模板id
//        spuDTO.setDeliveryTemplateId(null);
//        //获取商家代销设置
//        ServerResponseEntity<ShopSubstituteSalesVO> salesType = shopSubstituteSalesFeignClient.getByShopSubstituteSalesId(shopId);
//        ShopSubstituteSalesVO shopSubstituteSalesVO = salesType.getData();
//        if (!Objects.isNull(shopSubstituteSalesVO)){
//            if (shopSubstituteSalesVO.getSalesType() == 0){
//                //智能设价计算售价
//                Long price = 0L;
//                if (Objects.equals(shopSubstituteSalesVO.getSalesPriceType(),SalesPriceType.PROPORTION_PRICE.value())){
//                    //按比例加价
//                    price = PriceUtil.divideByBankerRounding(spuDTO.getPriceFee() * shopSubstituteSalesVO.getSalesPrice(),10000) + spuDTO.getPriceFee();
//                }
//                if (Objects.equals(shopSubstituteSalesVO.getSalesPriceType(),SalesPriceType.FIXED_NUMBER_PRICE.value())){
//                    //按固定数值加价
//                    price = spuDTO.getPriceFee() + shopSubstituteSalesVO.getSalesPrice();
//                }
//                spuDTO.setPriceFee(price);
//                spuDTO.setMarketPriceFee(price);
//            }
//        }
//        spuDTO.setScoreFee(Objects.isNull(spuDTO.getScoreFee()) ? Constant.ZERO_LONG : spuDTO.getScoreFee());
//        //保存商品信息
//        Spu spu = mapperFacade.map(spuDTO, Spu.class);
//        spuMapper.save(spu);
//        //查询供应商商品属性
//        List<SpuAttrValueVO> spuAttrs = spuAttrValueService.getSpuAttrsBySpuId(supplierSpuId);
//        List<SpuAttrValueDTO> spuAttrValueDTOS = new ArrayList<>();
//        for (SpuAttrValueVO spuAttr : spuAttrs) {
//            SpuAttrValueDTO spuAttrValueDTO = new SpuAttrValueDTO();
//            spuAttr.setSpuId(spu.getSpuId());
//            spuAttrValueDTO.setAttrId(spuAttr.getAttrId());
//            spuAttrValueDTO.setAttrName(spuAttr.getSpuAttrValueLangList().get(0).getAttrName());
//            spuAttrValueDTO.setAttrValueName(spuAttr.getSpuAttrValueLangList().get(0).getAttrValueName());
//            if (!Objects.isNull(spuAttr.getAttrValueId())){
//                spuAttrValueDTO.setAttrValueId(spuAttr.getAttrValueId());
//            }
//            spuAttrValueDTOS.add(spuAttrValueDTO);
//        }
//        // 2.保存商品属性信息
//        spuAttrValueService.save(spu.getSpuId(), spu.getCategoryId(), spuAttrValueDTOS);
//        // 3.国际化信息、商品详情
//        spuDTO.setSpuId(spu.getSpuId());
//        spuServiceImpl.loadSpuLangInfo(spuDTO, Boolean.TRUE);
//        //保存商品扩展信息
//        SpuExtension spuExtension = new SpuExtension();
//        spuExtension.setSpuId(spu.getSpuId());
//        spuExtension.setActualStock(0);
//        spuExtension.setStock(0);
//        spuExtensionService.save(spuExtension);
//        //sku信息
//        List<SkuVO> skuVOS = skuMapper.listSkuWithAttrBySpuId(spuId);
//        List<SkuDTO> skuDTOs = new ArrayList<>();
//        for (SkuVO skuVO : skuVOS) {
//            if (shopSubstituteSalesVO.getSalesType() == 0){
//                //智能设价计算售价
//                Long price = 0L;
//                if (Objects.equals(shopSubstituteSalesVO.getSalesPriceType(),SalesPriceType.PROPORTION_PRICE.value())){
//                    //按比例加价
//                    price = PriceUtil.divideByBankerRounding(skuVO.getPriceFee() * shopSubstituteSalesVO.getSalesPrice(),10000) + skuVO.getPriceFee();
//                }
//                if (Objects.equals(shopSubstituteSalesVO.getSalesPriceType(),SalesPriceType.FIXED_NUMBER_PRICE.value())){
//                    //按固定数值加价
//                    price = skuVO.getPriceFee() + shopSubstituteSalesVO.getSalesPrice();
//                }
//                skuVO.setPriceFee(price);
//                skuVO.setMarketPriceFee(price);
//            }
//            SkuDTO skuDTO = mapperFacade.map(skuVO, SkuDTO.class);
//            skuDTO.setSupplierSkuId(skuDTO.getSkuId());
//            skuDTO.setSpuId(null);
//            skuDTO.setStock(0);
//            skuDTOs.add(skuDTO);
//        }
//        //保存sku信息
//        skuService.save(spu.getSpuId(), skuDTOs);
//        // 更新品牌信息
//        brandService.updateSpuCount(spu.getBrandId(), AuthUserContext.get().getSysType());
//    }


}
